package com.sts.transform.function;

import cn.hutool.core.util.StrUtil;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorString;

import java.util.List;
import java.util.Map;

/**
 * @author lsl
 * @since 2025年07月09日 19:59
 */
public class RowGetFunction extends AbstractFunction {

    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
        List<String> list = (List<String>) FunctionUtils.getJavaObject(arg1, env);
        Number numberValue = FunctionUtils.getNumberValue(arg2, env);
        int index = numberValue.intValue();
        String value = list.get(index);

        String mock = (String) env.get("mock");
        if (StrUtil.startWith(value, mock)) {
            value = StrUtil.subAfter(value, mock, false);
            Object executeValue = AviatorEvaluator.execute(value, env, true);
            if (executeValue != null) {
                value = String.valueOf(executeValue);
                list.set(index, value);
            }
        }
        return new AviatorString(value);
    }

    @Override
    public String getName() {
        return "row.get";
    }
}
